	import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.ArrayList;
import java.util.HashMap;

import stub.Product;
import stub.Warehouse;


public class WarehouseImpl extends UnicastRemoteObject implements Warehouse{
	
	private ArrayList<Product>		products;
	private HashMap<Integer, Order>	orders;
	private int						sessionId	= 0;
	
	
	public WarehouseImpl() throws RemoteException {
		products = new ArrayList<Product>();
		orders = new HashMap<Integer, Order>();
		
		// Add products
		products.add( new ProductImpl( "Fiets", "algemeen", 10.99 ) );
		products.add( new ProductImpl( "auto", "algemeen", 130.99 ) );
		products.add( new ProductImpl( "geluidsinstallatie", "electronica", 300.99 ) );
		products.add( new ProductImpl( "laptop", "electronica", 600.99 ) );
		products.add( new ProductImpl( "eten", "eten", 2.99 ) );
	}
	
	
	@Override
	public ArrayList<Product> getProducten() throws RemoteException {
		return products;
	}
	
	
	@Override
	public ArrayList<String> getProductTypes() throws RemoteException {
		ArrayList<String> types = new ArrayList<String>();
		for( Product p : products ){
			if( !types.contains( p.getType() ) ){
				types.add( p.getType() );
			}
		}
		return types;
	}
	
	
	@Override
	public ArrayList<Product> getProducten( String type ) throws RemoteException {
		ArrayList<Product> productMatches = new ArrayList<Product>();
		for( Product p : products ){
			if( p.getType().equals( type ) ){
				productMatches.add( p );
			}
		}
		return productMatches;
	}
	
	
	@Override
	public synchronized int newOrder( String customerName ) throws RemoteException {
		sessionId++;
		orders.put( sessionId, new Order( customerName ) );
		return sessionId;
	}
	
	
	@Override
	public boolean order( String customerName, int orderNr, String productName, int amount ) throws RemoteException {
		Order order = orders.get( orderNr );
		order.addProduct( findProductByName( productName ), amount );
		orders.put( orderNr, order );
		return true;
	}
	
	public Product findProductByName(String productName) throws RemoteException{
		Product foundProduct = null;
		for(Product p: products){
			if( p.getName().equals( productName )) {
				foundProduct = p;
				break;
			}
		}
		return foundProduct;
	}

	public HashMap<Integer, Order> getOrders(){
		return orders;
	}

	@Override
	public HashMap<Product, Integer> getOrderOverview( String customerName, int orderNr ) throws RemoteException {
		return orders.get( orderNr ).getProductsOverview();
	}


	@Override
	public double getTotalPriceForOrder( String customerName, int orderNr ) throws RemoteException {
		return orders.get(orderNr).getTotalPrice();
	}


	@Override
	public boolean secureOrder( String customerName, int orderNr ) throws RemoteException {
		return orders.get(orderNr).orderSecured();
	}
	
}
